<?php

namespace app\Http\Controllers\admins;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Setting extends controller
{
    // 表单
    private function form($field = [])
    {
        $form = [
            ['label' => '站点Logo', 'name' => 'logo', 'type' => 'upload'],
            ['label' => '站点名称', 'name' => 'siteName', 'required' => true, 'value' => 'laravel测试'],
            ['label' => '站点域名', 'name' => 'siteUrl', 'value' => '', 'placeholder' => '默认相对路径', 'desc' => '如 https://www.baidu.com'],
            ['label' => 'SEO标题', 'name' => 'title', 'required' => true, 'value' => 'laravel title'],
            ['label' => 'SEO描述', 'name' => 'description', 'type' => 'textarea', 'required' => true, 'value' => 'laravel description'],
            ['label' => '底部小导航', 'name' => 'minNav', 'type' => 'textarea', 'value' => '<span class="layui-breadcrumb" lay-separator="|">
            <a href="">小导航1</a>
            <a href="">小导航2</a>
            <a href="">小导航3</a>
            <a href="">小导航4</a>
          </span>'],
            ['label' => '版权信息', 'name' => 'copyright', 'type' => 'textarea', 'value' => 'Copyright © ' . date('Y')],
            ['label' => '上传类型', 'name' => 'exts', 'value' => 'gif|jpg|jpeg|png|zip', 'desc' => '允许上传的文件类型'],
            ['label' => '限制大小', 'name' => 'size', 'type' => 'number', 'verify' => 'required|number', 'value' => '10240', 'desc' => '单位 KB 默认最大 10MB'],
            ['label' => '蜘蛛不索引', 'name' => 'robots', 'type' => 'switch'],
            ['label' => 'ICP备案号', 'name' => 'icp'],
        ];
        if ($field) {
            if (count($field) === count($field, 1)) {
                array_push($form, $field);
            } else {
                $form = array_merge($form, $field);
            }
        }
        return $form;
    }

    // 高级设置
    private function advanced()
    {
        return [
            ['label' => '默认图像', 'name' => 'avatar', 'type' => 'upload', 'desc' => '用户无图像时默认图像'],
            ['label' => '轮播图1', 'name' => 'slide1', 'type' => 'upload'],
            ['label' => '链接地址', 'name' => 'slide_url1'],
            ['label' => '轮播图2', 'name' => 'slide2', 'type' => 'upload'],
            ['label' => '链接地址', 'name' => 'slide_url2'],
            ['label' => '轮播图3', 'name' => 'slide3', 'type' => 'upload'],
            ['label' => '链接地址', 'name' => 'slide_url3'],
            ['label' => '轮播图4', 'name' => 'slide4', 'type' => 'upload'],
            ['label' => '链接地址', 'name' => 'slide_url4'],
            ['label' => '轮播图5', 'name' => 'slide5', 'type' => 'upload'],
            ['label' => '链接地址', 'name' => 'slide_url5'],
        ];
    }

    // 其它设置
    private function other()
    {
        return [
            ['label' => '热门文章', 'name' => 'hots', 'type' => 'number', 'value' => 5, 'desc' => '条显示'],
            ['label' => '相关文章', 'name' => 'related', 'type' => 'number', 'value' => 4, 'desc' => '条显示'],
            ['label' => '图片分类', 'name' => 'grid', 'type' => 'select', 'value' => 0, 'options' => $this->cat_tree()],
            ['label' => '评论嵌套', 'name' => 'commentsLevel', 'type' => 'number', 'value' => 5, 'desc' => '层最多'],
            ['label' => '内容声明', 'name' => 'statement', 'type' => 'textarea', 'rows' => 3, 'value' => '<p>本文链接：{url}</p>
            <p>转载声明：本站文章若无特别说明，皆为原创，转载请注明来源！</p>'],
        ];
    }

    // 提交按钮
    private function submit()
    {
        return [
            ['type' => 'submit', 'value' => '保存']
        ];
    }

    public function index()
    {
        $db = DB::table('setting')->where('names', 'setting')->first();
        $default = $db ? json_decode($db->values) : null;
        $args = ['url' => '/admins/setting/save', 'reload' => 'location', 'upload' => '/admins/files/uploads'];
        $data['title'] = '网站设置';
        // 构建tab表单
        $form = $this->form();
        $data['form'] = $this->build_form($form, $default);
        $data['advanced'] = $this->build_form($this->advanced(), $default);
        $data['other'] = $this->build_form($this->other(), $default);
        $data['submit'] = $this->build_form($this->submit(), $default);
        // 构建脚本
        $form = array_merge($form, $this->advanced());
        $form = array_merge($form, $this->other());
        $form = array_merge($form, $this->submit());
        $data['script'] = $this->build_script($form, $args);
        return view('/admins/setting/index', $data);
    }

    public function save(Request $request)
    {
        $form = $this->form();
        $form = array_merge($form, $this->advanced());
        $form = array_merge($form, $this->other());
        $data = $this->check($form, $request);
        if (!is_array($data)) return $data;
        $values = json_encode($data);
        $db = DB::table('setting')->where('names', 'setting')->first();
        if ($db)
            DB::table('setting')->where('names', 'setting')->update(['values' => $values]);
        else
            DB::table('setting')->insert(['names' => 'setting', 'values' => $values]);
        if (preg_match_all('#["\'](/storage/.+?\.[^"\']*)["\']#i', str_replace('\\', '', $values), $matches)) {
            foreach (array_unique($matches[1]) as $match) {
                DB::table('files')->where('path', $match)->update(['status' => 0]);
            }
        }
        return $this->errMsg(0, '保存成功');
    }

    // 无限层级分类树
    private function cat_tree()
    {
        $db = DB::table('cat')
            ->where('status', 0)
            ->orderBy('id', 'asc')
            ->orderBy('order', 'desc')
            ->get()
            ->all();
        $db = $this->trees($db);
        $db = array_reduce($db, function ($res, $next) {
            $res[$next->id] = $next->level ? str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", $next->level) . "|— " . $next->name : $next->name;
            return $res;
        }, []);
        $db = array_merge([0 => '&mdash; 请选择 &mdash;'], $db);
        return $db;
    }
}
